<template>
  <div class="schedule-plan-detail-page">
    <div class="page-header">
      <el-row :gutter="20">
        <el-col :span="18">
          <h1>{{ pageTitle }}</h1>
          <p class="subtitle">{{ algorithmDisplayName }} - {{ planStatus }}</p>
        </el-col>
        <el-col :span="6" class="header-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button 
            v-if="planData?.status === '草稿'" 
            type="warning" 
            @click="confirmPlan"
            :loading="confirming"
          >
            确认计划
          </el-button>
          <el-button 
            v-if="planData?.status !== '执行中'" 
            type="danger" 
            @click="deletePlan"
            :loading="deleting"
          >
            删除计划
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div v-if="planData" class="page-content">
      <!-- 计划基本信息 -->
      <el-card class="info-card" style="margin-bottom: 20px;">
        <template #header>
          <h3>计划基本信息</h3>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">计划ID</div>
              <div class="info-value">{{ planData.planId }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">计划名称</div>
              <div class="info-value">{{ planData.planName }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">状态</div>
              <div class="info-value">
                <el-tag :type="getStatusTagType(planData.status)">{{ planData.status }}</el-tag>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">设备利用率</div>
              <div class="info-value">{{ utilization }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">创建人</div>
              <div class="info-value">{{ planData.createdBy }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">创建时间</div>
              <div class="info-value">{{ planData.createTime }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">确认时间</div>
              <div class="info-value">{{ planData.confirmTime || '未确认' }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <div class="info-label">算法类型</div>
              <div class="info-value">{{ algorithmDisplayName }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <div class="info-item">
              <div class="info-label">计划开始时间</div>
              <div class="info-value">{{ planData.planStartTime }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <div class="info-label">计划结束时间</div>
              <div class="info-value">{{ planData.planEndTime }}</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 统计信息 -->
      <el-card class="stats-card" style="margin-bottom: 20px;">
        <template #header>
          <h3>统计信息</h3>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ planData.totalTasks || planDetails.productionTasks?.length || 0 }}</div>
              <div class="stat-label">生产任务数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ planData.totalScheduleDetails || planDetails.scheduleDetails?.length || 0 }}</div>
              <div class="stat-label">排产详情数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ planData.totalMachines || uniqueMachines.length }}</div>
              <div class="stat-label">涉及机器数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ planData.totalWorkOrders || uniqueWorkOrders.length }}</div>
              <div class="stat-label">涉及工单数</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 甘特图 -->
      <div class="gantt-section" style="margin-bottom: 20px;">
        <schedule-gantt-chart 
          ref="ganttChartRef"
          :plan-data="planData"
          :production-tasks="planDetails.productionTasks"
          :schedule-details="planDetails.scheduleDetails"
        />
      </div>

      <!-- 详细数据表格 -->
      <el-card class="table-card">
        <template #header>
          <h3>详细数据</h3>
        </template>
        <el-tabs v-model="activeTab" type="card">
          <!-- 生产任务标签页 -->
          <el-tab-pane label="生产任务" name="tasks">
            <el-table 
              :data="planDetails.productionTasks" 
              border 
              stripe
              height="500"
              style="width: 100%"
              v-loading="loadingDetails"
            >
              <el-table-column prop="taskId" label="任务ID" width="150" fixed="left" sortable />
              <el-table-column prop="workOrderId" label="工单ID" width="150" sortable />
              <el-table-column prop="operationId" label="工序ID" width="150" sortable />
              <el-table-column prop="machineId" label="机器ID" width="120" sortable />
              <el-table-column prop="quantity" label="数量" width="80" sortable />
              <el-table-column prop="standardTime" label="标准时间(分)" width="120" sortable />
              <el-table-column prop="plannedTime" label="计划时间(分)" width="120" sortable />
              <el-table-column prop="status" label="状态" width="100" sortable>
                <template #default="scope">
                  <el-tag :type="getTaskStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="planStartTime" label="计划开始" width="140" sortable />
              <el-table-column prop="planEndTime" label="计划结束" width="140" sortable />
              <el-table-column prop="actualStartTime" label="实际开始" width="140" sortable />
              <el-table-column prop="actualEndTime" label="实际结束" width="140" sortable />
            </el-table>
          </el-tab-pane>

          <!-- 排产详情标签页 -->
          <el-tab-pane label="排产详情" name="details">
            <el-table 
              :data="planDetails.scheduleDetails" 
              border 
              stripe
              height="500"
              style="width: 100%"
              v-loading="loadingDetails"
            >
              <el-table-column prop="detailId" label="详情ID" width="150" fixed="left" sortable />
              <el-table-column prop="taskId" label="任务ID" width="150" sortable />
              <el-table-column prop="machineId" label="机器ID" width="120" sortable />
              <el-table-column prop="scheduledStartTime" label="排产开始时间" width="160" sortable />
              <el-table-column prop="scheduledEndTime" label="排产结束时间" width="160" sortable />
              <el-table-column prop="sequenceNo" label="排产序号" width="100" sortable />
              <el-table-column prop="createTime" label="创建时间" width="160" sortable />
            </el-table>
          </el-tab-pane>

          <!-- 工单信息标签页 -->
          <el-tab-pane label="关联工单" name="workorders">
            <el-table 
              :data="workOrdersData" 
              border 
              stripe
              height="500"
              style="width: 100%"
              v-loading="loadingDetails"
            >
              <el-table-column prop="workOrderId" label="工单ID" width="150" fixed="left" sortable />
              <el-table-column prop="orderItemId" label="订单项ID" width="150" sortable />
              <el-table-column prop="productId" label="产品ID" width="120" sortable />
              <el-table-column prop="quantity" label="生产数量" width="100" sortable />
              <el-table-column prop="priority" label="优先级" width="100" sortable>
                <template #default="scope">
                  <el-tag :type="getPriorityTagType(scope.row.priority)">
                    {{ getPriorityText(scope.row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="120" sortable>
                <template #default="scope">
                  <el-tag :type="getWorkOrderStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="planStartTime" label="计划开始" width="140" sortable />
              <el-table-column prop="planEndTime" label="计划结束" width="140" sortable />
              <el-table-column prop="createTime" label="创建时间" width="140" sortable />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="loadError" class="error-container">
      <el-empty 
        :description="errorMessage" 
        image="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png"
      >
        <el-button type="primary" @click="loadPlanDetail">重新加载</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-empty>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-loading-service 
        v-loading="true" 
        element-loading-text="正在加载排产计划详情..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-empty description="正在加载计划详情...">
          <el-button type="primary" @click="goBack">返回</el-button>
        </el-empty>
      </el-loading-service>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import ScheduleGanttChart from '@/components/ScheduleGanttChart.vue';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const ganttChartRef = ref(null);

const API_BASE_URL = 'http://117.72.45.141:8091';

const planData = ref(null);
const planDetails = ref({
  productionTasks: [],
  scheduleDetails: []
});
const workOrdersData = ref([]);
const activeTab = ref('tasks');
const loadingDetails = ref(false);
const confirming = ref(false);
const deleting = ref(false);
const loadError = ref(false);
const errorMessage = ref('');



// 算法名称映射
const algorithmNameMap = {
  'PRODUCT_BATCH': '同种产品集中生产算法', 
  'MACHINE_UTILIZATION': '负载均衡算法',
  'ENHANCED_GENETIC_ALGORITHM': '增强遗传算法',
  'DEFAULT_FIFO': 'FIFO默认排序算法',
  'CRITICAL_PATH_SPT': '关键路径SPT算法',
  "COMBINE_ALGORITHM": '紧急优先与机器利用率结合算法'
};

// 计算属性
const pageTitle = computed(() => {
  return planData.value?.planName || '计划详情';
});

const algorithmDisplayName = computed(() => {
  const algorithm = planData.value?.algorithmType;
  return algorithmNameMap[algorithm] || algorithm || '未知算法';
});

const planStatus = computed(() => {
  return planData.value?.status || '未知状态';
});

const utilization = computed(() => {
  return planData.value?.totalUtilization 
    ? (planData.value.totalUtilization).toFixed(1) + '%'
    : '-';
});

// 统计计算 - 优先使用接口返回的统计数据，如果没有则从详情数据计算
const uniqueMachines = computed(() => {
  // 如果有接口返回的机器数量统计，直接使用
  if (planData.value?.totalMachines) {
    return Array.from({ length: planData.value.totalMachines }, (_, i) => `机器${i + 1}`);
  }
  
  // 否则从详情数据中计算
  const machines = new Set();
  planDetails.value.productionTasks?.forEach(task => {
    if (task.machineId) machines.add(task.machineId);
  });
  planDetails.value.scheduleDetails?.forEach(detail => {
    if (detail.machineId) machines.add(detail.machineId);
  });
  return Array.from(machines);
});

const uniqueWorkOrders = computed(() => {
  // 如果有接口返回的工单数量统计，直接使用
  if (planData.value?.totalWorkOrders) {
    return Array.from({ length: planData.value.totalWorkOrders }, (_, i) => `工单${i + 1}`);
  }
  
  // 否则从详情数据中计算
  const workOrders = new Set();
  planDetails.value.productionTasks?.forEach(task => {
    if (task.workOrderId) workOrders.add(task.workOrderId);
  });
  return Array.from(workOrders);
});

// 加载计划详情
const loadPlanDetail = async () => {
  const planId = route.params.planId;
  if (!planId) {
    ElMessage.error('计划ID不存在');
    goBack();
    return;
  }

  console.log('加载计划详情，planId:', planId);
  loadingDetails.value = true;
  loadError.value = false;
  errorMessage.value = '';

  try {
    // 获取完整的计划详情数据
    console.log('请求计划详情:', `${API_BASE_URL}/api/schedule/plans/${planId}`);
    const response = await axios.get(`${API_BASE_URL}/api/schedule/plans/${planId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.code === 200) {
      const data = response.data.data;
      console.log('接收到的计划详情数据:', data);
      
      // 设置基本计划信息 - 注意接口返回的是 SchedulePlan 而不是直接的计划数据
      planData.value = data.SchedulePlan || data.schedulePlan || data;
      
      // 设置排产详细数据
      planDetails.value = {
        productionTasks: data.productionTasks || [],
        scheduleDetails: data.scheduleDetails || []
      };
      
      // 设置工单数据
      workOrdersData.value = data.workOrders || [];
      
      // 设置统计信息（如果基本信息中没有的话，从接口数据中补充）
      if (!planData.value.totalTasks) {
        planData.value.totalTasks = data.totalTasks;
      }
      if (!planData.value.totalScheduleDetails) {
        planData.value.totalScheduleDetails = data.totalScheduleDetails;
      }
      if (!planData.value.totalMachines) {
        planData.value.totalMachines = data.totalMachines;
      }
      if (!planData.value.totalWorkOrders) {
        planData.value.totalWorkOrders = data.totalWorkOrders;
      }
      
      console.log('处理后的计划数据:', planData.value);
      console.log('处理后的详情数据:', planDetails.value);
      console.log('处理后的工单数据:', workOrdersData.value);
      
    } else {
      loadError.value = true;
      errorMessage.value = response.data.message || '获取计划详情失败';
      ElMessage.error(errorMessage.value);
    }
  } catch (error) {
    console.error('加载计划详情失败:', error);
    loadError.value = true;
    errorMessage.value = '加载计划详情失败，请检查网络连接';
    ElMessage.error(errorMessage.value);
  } finally {
    loadingDetails.value = false;
  }
};





// 确认计划
const confirmPlan = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要确认排产计划 "${planData.value.planName}" 吗？确认后将开始执行该计划。`,
      '确认排产计划',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    confirming.value = true;
    const response = await axios.put(`${API_BASE_URL}/api/schedule/confirm/${planData.value.planId}`, null, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('排产计划确认成功');
      // 重新加载计划详情
      loadPlanDetail();
    } else {
      ElMessage.error(response.data.message || '确认失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认排产计划失败:', error);
      ElMessage.error('确认失败，请检查网络连接');
    }
  } finally {
    confirming.value = false;
  }
};

// 删除计划
const deletePlan = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除排产计划 "${planData.value.planName}" 吗？此操作不可逆。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    deleting.value = true;
    const response = await axios.delete(`${API_BASE_URL}/api/schedule/plans/${planData.value.planId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('排产计划删除成功');
      goBack();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除排产计划失败:', error);
      ElMessage.error('删除失败，请检查网络连接');
    }
  } finally {
    deleting.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.push('/scheduling');
};

// 状态标签类型
const getStatusTagType = (status) => {
  const types = {
    '草稿': 'info',
    '已确认': 'success',
    '执行中': 'warning',
    '已完成': 'primary'
  };
  return types[status] || 'default';
};

const getTaskStatusTagType = (status) => {
  const types = {
    '待分配': 'info',
    '已分配': 'warning',
    '进行中': 'primary',
    '已完成': 'success'
  };
  return types[status] || 'default';
};

const getWorkOrderStatusTagType = (status) => {
  const types = {
    '待排产': 'info',      // 灰色
    '已排产': 'primary',   // 蓝色
    '生产中': 'danger',    // 红色
    '生产完成': 'success'  // 绿色
  };
  return types[status] || 'default';
};

const getPriorityTagType = (priority) => {
  const types = {
    1: 'danger',  // 高优先级
    2: 'warning', // 中优先级
    3: 'info'     // 低优先级
  };
  return types[priority] || 'default';
};

const getPriorityText = (priority) => {
  const texts = {
    1: '高',
    2: '中',
    3: '低'
  };
  return texts[priority] || '未知';
};

// 组件挂载时加载数据
onMounted(() => {
  loadPlanDetail();
  
  // 延迟初始化甘特图
  setTimeout(() => {
    if (ganttChartRef.value) {
      ganttChartRef.value.init();
    }
  }, 1000);
});
</script>

<style scoped>
.schedule-plan-detail-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 5px 0;
  color: #409eff;
  font-size: 24px;
}

.subtitle {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.page-content {
  max-width: 1400px;
  margin: 0 auto;
}

.info-card h3,
.stats-card h3,
.gantt-card h3,
.table-card h3 {
  margin: 0;
  color: #409eff;
  font-weight: 600;
}

.info-item {
  padding: 10px 0;
}

.info-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.info-value {
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.gantt-card {
  min-height: 600px;
}

.table-card {
  margin-bottom: 20px;
}

.el-tabs {
  margin-top: 10px;
}
</style> 